package config

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
	"io"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"
)

func initLog() {
	var (
		exePath string
		err     error
	)
	if exePath, err = os.Executable(); err != nil {
		fmt.Println(err)
	}
	//日志文件
	fileName := path.Join(filepath.Dir(exePath), GlobalCfg.Log.Name)
	if _, err := os.Stat(fileName); err != nil {
		if _, err := os.Create(fileName); err != nil {
			fmt.Println(err.Error())
		}
	}
	logrus.SetOutput(io.MultiWriter(&lumberjack.Logger{
		Filename:   fileName,
		MaxSize:    100, // megabytes
		MaxBackups: 3,
		MaxAge:     7,    //days
		Compress:   true, // disabled by default
	}, os.Stdout))

	// 记录调用方法名
	logrus.SetReportCaller(true)
	// 设置日志级别
	switch GlobalCfg.Log.Lv {
	case "panic":
		logrus.SetLevel(logrus.PanicLevel)
	case "info":
		logrus.SetLevel(logrus.InfoLevel)
	case "err":
		logrus.SetLevel(logrus.ErrorLevel)
	default:
		logrus.SetLevel(logrus.DebugLevel)
	}
	// 日志格式化
	logrus.SetFormatter(new(Formatter))
}

type Formatter struct{}

func (s *Formatter) Format(entry *logrus.Entry) ([]byte, error) {
	timestamp := time.Now().Local().Format("2006-01-02 15:04:05")
	msg := fmt.Sprintf("%s %s %s:%d %s\n", timestamp, strings.ToUpper(entry.Level.String()), entry.Caller.File, entry.Caller.Line, entry.Message)
	return []byte(msg), nil
}
